package com.masonluo.mlonlinejudge.controller;

import com.masonluo.mlonlinejudge.dao.UserInfoRepository;
import com.masonluo.mlonlinejudge.enums.RolesEnum;
import com.masonluo.mlonlinejudge.mapper.UserInfoMapper;
import com.masonluo.mlonlinejudge.mapper.UserMapper;
import com.masonluo.mlonlinejudge.model.bo.UserBo;
import com.masonluo.mlonlinejudge.model.dto.LoginInfoDto;
import com.masonluo.mlonlinejudge.model.bo.UserRankBo;
import com.masonluo.mlonlinejudge.model.dto.UserDto;
import com.masonluo.mlonlinejudge.model.dto.UserInfoDto;
import com.masonluo.mlonlinejudge.model.param.UserInfoQueryParam;
import com.masonluo.mlonlinejudge.model.param.UserParam;
import com.masonluo.mlonlinejudge.result.Result;
import com.masonluo.mlonlinejudge.result.ResultCode;
import com.masonluo.mlonlinejudge.service.UserService;
import com.masonluo.mlonlinejudge.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Objects;

/**
 * @author masonluo
 * @date 2021/2/9 11:22 下午
 */
@RestController
@RequestMapping("/user")
@Api(value = "用户模块", tags = "user")
public class UserController {

    @Autowired
    private UserService userService;


    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserInfoRepository userInfoRepository;

//    @PostMapping
//    @RequestMapping("/register")
//    public Result<UserInfoVo> register(@RequestBody @Valid UserParam userParam) {
//        UserInfoDto userInfoDto = userService.register(userParam.getUsername(), userParam.getPassword());
//        return Result.created(userInfoMapper.dtoToVo(userInfoDto));
//    }

//    @PostMapping
//    @RequestMapping("/login")
//    public Result<LoginVo> login(@RequestBody @Valid UserParam userParam) {
//        LoginDto dto = userService.login(userParam.getUsername(), userParam.getPassword());
//        return Result.ok(userMapper.loginDtoToLoginVo(dto));
//    }

    @PostMapping("/login")
    @ApiOperation("登录接口")
    public Result login(@RequestBody @Valid UserParam userParam) {
        if (userParam.getSchoolId() == null){
            throw new IllegalArgumentException("请选择学校");
        }
        if (userParam.getUsername() == null || userParam.getPassword() == null) {
            throw new IllegalArgumentException("用户名或密码不可为空");
        }
        LoginInfoDto loginInfoDto = userService.login(userParam.getUsername(), userParam.getPassword(),userParam.getSchoolId());
        return Result.ok(loginInfoDto);

    }

    @PostMapping("/getUSerInfoByNickOrName")
    @ApiOperation("根据用户昵称或用户名查找用户信息")
    public Result<UserInfoDto> getUserInfoByNickOrName(@RequestBody UserInfoQueryParam param) {
        if (Objects.isNull(param.getPageNum()) || param.getPageNum() == 0) {
            param.setPageNum(1);
        }
        if (Objects.isNull(param.getPageSize()) || param.getPageSize() == 0) {
            param.setPageSize(10);
        }
        List<UserInfoDto> userInfoDtoList = userService.queryPageUserInfoByNickOrName(param);
        Integer total = userService.getTotalByNickOrNameKey(param.getSchoolId(),param.getUsernameKey(),param.getNicknameKey(),param.getRole());
        return new Result(ResultCode.OK, "用户信息查找成功", userInfoDtoList, param.getPageNum(), param.getPageSize(), total);
    }

    @PostMapping("/userIsRepeat")
    @ApiOperation("判断用户是否重复")
    public Result userIsRepeat(@RequestBody List<UserDto> userDtoList) {
        userDtoList.forEach(userDto -> {
            if (Objects.isNull(userDto.getUsername())) {
                throw new IllegalArgumentException("用户名不可为空");
            }
        });
        List<String> nameDuplicate = userService.checkUserNameDuplicate(userDtoList);
        for (UserDto user : userDtoList) {
            for (String name :nameDuplicate) {
                if (user.getUsername().equals(name)){
                    user.setStatus(false);
                }
            }
        }
        return new Result(ResultCode.OK, userDtoList);
    }

    @PostMapping("/addUserList")
    @ApiOperation("添加用户")
    public Result addUSerList(@RequestBody List<UserDto> userDtoList) {
        userDtoList.forEach(userDto -> {
            if (Objects.isNull(userDto.getUsername())) {
                throw new IllegalArgumentException("用户名不可为空");
            }
            if (Objects.isNull(userDto.getPassword())) {
                throw new IllegalArgumentException("用户密码不可为空");
            }
            if (Objects.isNull(userDto.getRole())) {
                throw new IllegalArgumentException("用户角色不可为空");
            }
        });
        if (!userService.checkUserSchoolExist(userDtoList)) {
            throw new IllegalArgumentException("学校不存在");
        }
        if (!userService.checkUserClassExist(userDtoList)) {
            throw new IllegalArgumentException("班级不存在");
        }
        List<String> nameDuplicate = userService.checkUserNameDuplicate(userDtoList);
        userService.addUserList(userDtoList,nameDuplicate);
        return Result.ok("用户添加成功");
    }

    @PostMapping("/delete")
    @ApiOperation("根据用户id删除用户")
    public Result deleteUser(@RequestParam("userId") Integer userId) {
        if (Objects.isNull(userId)) {
            throw new IllegalArgumentException("用户iD不可为空");
        }
        userService.deleteUserById(userId);
        return Result.ok("用户删除成功");
    }

    @PostMapping("/update")
    @ApiOperation("更新用户信息")
    public Result updateUserInfo(@RequestBody UserDto userDto) {
        if (Objects.isNull(userDto.getUserId())) {
            throw new IllegalArgumentException("用户id不可为空");
        }
        UserBo userBo = userMapper.userDtoToUserBo(userDto);
        userService.updateUserInfo(userBo);
        return Result.ok();
    }

    @PostMapping("/getUserInfoByRole")
    @ApiOperation("获取学生/教师/校管理员信息列表[暂时不用]")
    public Result<List<UserInfoDto>> getUserInfoByRole(@RequestBody UserInfoQueryParam param) {
        if (Objects.isNull(param.getRole())) {
            throw new IllegalArgumentException("用户角色不可为空");
        }
        if (Objects.isNull(param.getPageNum()) || param.getPageNum() == 0) {
            param.setPageNum(1);
        }
        if (Objects.isNull(param.getPageSize()) || param.getPageSize() == 0) {
            param.setPageSize(10);
        }
        List<UserInfoDto> userInfoList = userService.queryPageUserInfoByRole(param);
        Integer roleId = RolesEnum.getRoleId(RolesEnum.getByName(param.getRole()));
        Integer total = userService.getTotalByRole(roleId);
        return new Result(ResultCode.OK, "用户信息查找成功", userInfoList, param.getPageNum(), param.getPageSize(), total);
    }

    @GetMapping("/getUserBySchoolId")
    @ApiOperation("根据学校id返回该学校的所有用户")
    public Result<List<UserInfoDto>> getUserBySchool(@RequestParam("schoolId") Integer schoolId,
                                                     @RequestParam("role") String role,
                                                     @RequestParam("pageNum") Integer pageNum,
                                                     @RequestParam("pageSize") Integer pageSize) {

        if (Objects.isNull(schoolId)) {
            throw new IllegalArgumentException("学校id不可为空");
        }
        if (StringUtils.isBlank(role)) {
            throw new IllegalArgumentException("用户角色不可为空");
        }
        if (Objects.isNull(pageNum) || pageNum == 0) {
            pageNum = 1;
        }
        if (Objects.isNull(pageSize) || pageSize == 0) {
            pageSize = 10;
        }
        List<UserInfoDto> userInfoDtoList = userService.queryPageUserBoBySchoolId(schoolId, role, pageNum, pageSize);
        Integer total = userService.getTotalBySchoolId(schoolId, role);
        return Result.ok(userInfoDtoList, "查找成功！", pageNum, pageSize, total);
    }

    @ApiOperation("根据学校id查询封神排行榜")
    @GetMapping("/getRankBySchoolId")
    public Result<List<UserRankBo>> getUserRankBySchoolId(@RequestParam("schoolId") Integer schoolId,
                                                          @RequestParam("pageNum") Integer pageNum,
                                                          @RequestParam("pageSize") Integer pageSize) {
        if (Objects.isNull(schoolId)) {
            throw new IllegalArgumentException("学校id不可为空");
        }
        if (Objects.isNull(pageNum) || pageNum == 0) {
            pageNum = 1;
        }
        if (Objects.isNull(pageSize) || pageSize == 0) {
            pageSize = 10;
        }
        List<UserRankBo> userRankList = userService.queryPageRankBySchoolId(schoolId, pageNum, pageSize);
        Integer total = userService.getTotalBySchoolId(schoolId,"STUDENT");
//        Integer total = 1;
        return Result.ok(userRankList, "查找成功！", pageNum, pageSize, total);
    }

}
